package com.c212.manager.aspect;


import com.c212.manager.bean.UserInfoEntity;
import com.c212.manager.constants.Consts;
import com.c212.manager.exception.AuthException;
import com.c212.manager.utils.UserContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Order(1)
@Component
public class UserAspect {
    private final static Logger logger = LoggerFactory.getLogger(AuthAspect.class);

    @Pointcut("execution(public * com.c212.manager.controller.*.*(..))" +
            "&& !execution(public * com.c212.manager.controller.UserController.*(..))")
    public void user() {
    }

    @Before("user()")
    public void doBefore(JoinPoint joinPoint) throws Exception {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info("url={}", request.getRequestURL());
        logger.info("method={}", request.getMethod());
        logger.info("ip={}", request.getRemoteAddr());
        logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        UserInfoEntity sessionUser = (UserInfoEntity) request.getSession().getAttribute("user");
        if(sessionUser !=null){
            UserContext.setUser(sessionUser);
        }
    }

    @AfterReturning(returning = "object", pointcut = "user()")
    public void doAfterReturning(Object object) throws JsonProcessingException {
        UserContext.remove();
        //logger.info("response={}", new ObjectMapper().writeValueAsString(object));
    }
}
